package prv.pursuivant.render.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import prv.pursuivant.render.Destination;
import prv.pursuivant.util.URLUtil;

public class MultipleFilesDestination implements Destination {

	private final String outputDir;
	protected FileWriter fileWriter = null;
	private final URLUtil urlUtil;

	public MultipleFilesDestination(String outputDir, URLUtil urlUtil) {
		this.outputDir = outputDir;
		this.urlUtil = urlUtil;
	}

	@Override
	public void startModel(String modelDescription) throws IOException {
	}

	@Override
	public void stopModel() throws IOException {
	}

	@Override
	public Writer startPage(String id) throws IOException {
		File dir = new File(outputDir);
		dir.mkdirs();
		File file = getFileForPage(id);
		fileWriter = new FileWriter(file);
		return fileWriter;
	}

	protected File getFileForPage(String id) {
		File file = new File(outputDir, "output." + id + ".html");
		return file;
	}

	@Override
	public void stopPage() throws IOException {
		fileWriter.close();
		fileWriter = null;
	}

	@Override
	public String getUriForPage(String id) {
		return urlUtil.escape("output." + id + ".html");
	}

}
